package com.systemsjr.mpf.account;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

import com.systemsjr.mpf.IntentHandler;
import com.systemsjr.mpf.MpfActivity;
import com.systemsjr.mpf.R;
import com.systemsjr.mpf.expense.Expense;

public class ManageAccountInstanceActivity extends Activity {
	private Cursor c;

	HashMap<String, Account> accountsMap = new HashMap<String, Account>();

	private int selectedItem = 1;

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			String selectedDate = "" + selectedYear;

			if (selectedMonth < 9) {
				selectedDate = selectedDate + "-0" + (selectedMonth + 1);
			} else {
				selectedDate = selectedDate + "-" + (selectedMonth + 1);
			}

			if (selectedDay < 9) {
				selectedDate = selectedDate + "-0" + selectedDay;
			} else {
				selectedDate = selectedDate + "-" + selectedMonth;
			}

			EditText dateText;

			if (selectedItem == 1) {
				dateText = (EditText) findViewById(R.id.startDate);
			} else {
				dateText = (EditText) findViewById(R.id.endDate);
			}

			dateText.setText(selectedDate);

			System.out.println("The date 2 is : " + selectedDate);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_manage_account_instance);

		final EditText startDate = (EditText) findViewById(R.id.startDate);
		final EditText endDate = (EditText) findViewById(R.id.endDate);
		final EditText instanceEdit = (EditText) findViewById(R.id.instanceDescription);
		final EditText budget = (EditText) findViewById(R.id.budget);

		budget.setText("0.00");

		final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

		final AutoCompleteTextView accountView = (AutoCompleteTextView) findViewById(R.id.instance_account);

		final AccountInstance instance = new AccountInstance();

		Cursor accountCursor = getContentResolver().query(Account.CONTENT_URI,
				Account.PROJECTIONS, null, null, null);
		String[] accounts = new String[accountCursor.getCount()];
		int i = 0;
		while (accountCursor.moveToNext()) {
			Account a = new Account();
			a.setId(accountCursor.getLong(accountCursor
					.getColumnIndex(Account.ID)));
			a.setCode(accountCursor.getString(accountCursor
					.getColumnIndex(Account.CODE)));
			a.setAccount(accountCursor.getString(accountCursor
					.getColumnIndex(Account.ACCOUNT)));

			accountsMap.put(a.getAccount(), a);
			accounts[i] = a.getAccount();
			i++;
		}
		accountCursor.close();

		ArrayAdapter<String> accountAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, accounts);

		accountView.setAdapter(accountAdapter);

		/**
		 * Change listener
		 */
		accountView.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				instanceEdit.setText(accountView.getText().toString() + " - "
						+ startDate.getText().toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		/**
		 * Adding listener to the start date
		 */
		startDate.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				instanceEdit.setText(accountView.getText().toString() + " - "
						+ startDate.getText().toString());

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		startDate.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					selectedItem = 1;
					DatePickerDialog dialog = getDate();
					dialog.show();
				}
			}
		});

		endDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				selectedItem = 2;
				DatePickerDialog dialog = getDate();
				dialog.show();
			}
		});

		Button saveButton = (Button) findViewById(R.id.saveAccountInstanceButton);
		saveButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				instance.setBudget(Double.parseDouble(budget.getText()
						.toString()));
				instance.setInstance(instanceEdit.getText().toString());
				instance.setAccount(accountsMap.get(accountView.getText()
						.toString()));

				try {
					if (startDate.getText().toString().length() == 10) {
						instance.setStartDate(sdf.parse(startDate.getText()
								.toString()));
					} else {
						instance.setStartDate(null);
					}

					if (endDate.getText().toString().length() == 10) {
						instance.setCloseDate(sdf.parse(endDate.getText()
								.toString()));
					} else {
						instance.setCloseDate(null);
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				ContentResolver cr = getContentResolver();
				ContentValues values = new ContentValues();
				values.put(AccountInstance.ACCOUNT_FK, instance.getAccount()
						.getId());
				values.put(AccountInstance.BUDGET, instance.getBudget());

				if (instance.getCloseDate() != null) {

					values.put(AccountInstance.CLOSE_DATE,
							sdf.format(instance.getCloseDate()));
				}

				if (instance.getStartDate() != null) {
					values.put(AccountInstance.START_DATE,
							sdf.format(instance.getStartDate()));
				}
				values.put(AccountInstance.INSTANCE, instance.getInstance());

				if (instance.getAccount() != null && instance.getBudget() > 0) {
					if (instance.getId() == null || instance.getId() == 0) {
						cr.insert(AccountInstance.CONTENT_URI, values);

						String s = AccountInstance.INSTANCE + " = '"
								+ instance.getInstance() + "' AND "
								+ AccountInstance.ACCOUNT_FK + " = "
								+ instance.getAccount().getId();
						Cursor c = cr.query(AccountInstance.CONTENT_URI,
								AccountInstance.PROJECTIONS, s, null, null);

						if (c.moveToFirst()) {
							instance.setId(c.getLong(c
									.getColumnIndex(AccountInstance.ID)));
						}

						c.close();

					} else {
						cr.update(AccountInstance.CONTENT_URI, values, "_id = "
								+ instance.getId(), null);
					}
				}

				AccountInstance ins = new AccountInstance(0, "", 0, null, null,
						null);

				showList(ins);
			}
		});

		Button newButton = (Button) findViewById(R.id.newAccountInstanceButton);
		newButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				instance.setStartDate(null);
				instance.setCloseDate(null);
				instance.setAccount(null);
				instance.setBudget(0);
				instance.setInstance(null);
			}
		});

		Button deleteButton = (Button) findViewById(R.id.deleteAccountInstanceButton);
		deleteButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ContentResolver cr = getContentResolver();
				if (instance.getId() != null || instance.getId() > 0) {
					cr.delete(AccountInstance.CONTENT_URI,
							"_id = " + instance.getId(), null);
				}

				accountView.setText(null);
				budget.setText("0.00");
				startDate.setText(null);
				endDate.setText(null);
				instanceEdit.setText(null);

				instance.setId(0L);
				try {
					instance.setStartDate(sdf.parse(startDate.getText()
							.toString()));
					instance.setCloseDate(sdf.parse(endDate.getText()
							.toString()));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				instance.setAccount(accountsMap.get(accountView.getText()
						.toString()));
				instance.setBudget(Double.parseDouble(budget.getText()
						.toString()));
				instance.setInstance(instanceEdit.getText().toString());

				AccountInstance ins = new AccountInstance(0, "", 0, null, null,
						null);

				showList(ins);
			}
		});

		Button searchButton = (Button) findViewById(R.id.searchAccountInstanceButton);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				instance.setBudget(budget.getText().toString().length() > 0 ? Double
						.parseDouble(budget.getText().toString()) : 0);
				instance.setInstance(instanceEdit.getText().toString());
				instance.setAccount(accountsMap.get(accountView.getText()
						.toString()));

				try {
					instance.setStartDate(sdf.parse(startDate.getText()
							.toString()));
					instance.setCloseDate(sdf.parse(endDate.getText()
							.toString()));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				AccountInstance inst = instance.clone();

				accountView.setText(null);
				budget.setText("0.00");
				startDate.setText(null);
				endDate.setText(null);
				instanceEdit.setText(null);

				instance.setStartDate(null);
				instance.setCloseDate(null);
				instance.setAccount(null);
				instance.setBudget(0.00);
				instance.setInstance(null);
				instance.setId(0L);

				showList(inst);
			}
		});

		/**
		 * If the hash map is empty, then set all editables to false
		 */
		if (accountsMap.size() == 0) {
			accountView.setEnabled(false);
			budget.setEnabled(false);
			startDate.setEnabled(false);
			endDate.setEnabled(false);
			instanceEdit.setEnabled(false);
		}
	}

	private DatePickerDialog getDate() {

		Calendar cal = Calendar.getInstance(TimeZone.getDefault());
		DatePickerDialog datePicker = new DatePickerDialog(this,
				R.style.AppBaseTheme, datePickerListener,
				cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
				cal.get(Calendar.DAY_OF_MONTH));

		datePicker.setCancelable(false);
		datePicker.setTitle("Select the date");

		return datePicker;
	}

	private void showList(AccountInstance instance) {
		Intent intent = new Intent(ManageAccountInstanceActivity.this,
				AccountInstanceList.class);
		if (instance != null) {
			intent.putExtra(AccountInstance.TABLE_NAME, instance);
		}

		startActivityForResult(intent, 1);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.manage_account_instance, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		Intent intent = IntentHandler.handleOnOptionsItemSelected(this,
				item.getItemId());
		startActivityForResult(intent, 1);
		return super.onOptionsItemSelected(item);
	}
}
